package com.bc.bcapi.service;

import com.bc.bcapi.dao.*;
import com.bc.bcapi.utils.web3j.Util;
import com.bc.bcmodel.enums.IntegralRecordEnum;
import com.bc.bcmodel.req.*;
import com.bc.commoncore.util.Digest;
import com.bc.commoncore.util.PageInfoExt;
import com.bc.bcmodel.domain.*;
import com.bc.bcmodel.resp.*;
import com.bc.commoncore.util.DateUtil;
import com.bc.commoncore.util.ExcelUtils;
import com.bc.commonentity.common.DBContextDbType;
import com.bc.commonentity.common.DBContextHolder;
import com.bc.commonentity.common.JsonResult;
import com.bc.commonentity.enums.HttpReturnRnums;
import com.bc.commonentity.enums.SeqNameEnum;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.math.BigInteger;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Name T_OrderService * @Description * @Author generation * @Date 2018/8/14 15:26:24 * @Version 1.0
 **/
@Service
public class T_OrderService {
    @Resource
    T_OrderMapper t_OrderMapper;
    @Resource
    T_ProjectMapper t_projectMapper;
    @Resource
    T_User_walletMapper t_user_walletMapper;
    @Resource
    T_SysconfService t_sysconfService;
    @Resource
    T_User_seller_bonusMapper t_User_seller_bonusMapper;
    @Resource
    T_SequenceService t_sequenceService;
    @Resource
    T_Account_logMapper t_account_logMapper;
    @Resource
    T_Wallet_infoMapper t_wallet_infoMapper;
    @Resource
    T_BalanceMapper t_balanceMapper;
    @Resource
    T_Order_kycMapper t_order_kycMapper;
    @Resource
    T_User_buyer_infoMapper t_user_buyer_infoMapper;
    @Resource
    T_Usdt_exchange_priceService t_usdt_exchange_priceService;
    @Resource
    T_Integral_recordService t_integral_recordService;
    @Resource
    T_Erc_contractMapper t_erc_contractMapper;

    /**
     * 保存单条数据     *      * @return
     */

    public int insert(T_OrderModel req) {
        return t_OrderMapper.insert(req);
    }

    /**
     * 批量增加数据     *      * @return
     */

    public int insertBatch(List<T_OrderModel> req) {
        return t_OrderMapper.insertBatch(req);
    }

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */

    public T_OrderModel findByNamedParam(T_OrderModel req) {
        return t_OrderMapper.findByNamedParam(req);
    }

    /**
     * 根据对象查询所有数据     *      * @return
     */

    public List<T_OrderModel> getAllList(T_OrderModel req) {
        return t_OrderMapper.findByNamedParamList(req);
    }

    /**
     * 根据对象查询所有分页数据     *      * @return
     */

    public PageInfo<MngOrderListResp> getList(MngOrderListReq req) {
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<MngOrderListResp> list = t_OrderMapper.getList(req);
        return new PageInfo<MngOrderListResp>(list);
    }

    /**
     * 更新指定对象     *      * @return
     */

    public int update(T_OrderModel req) {
        return t_OrderMapper.update(req);
    }

    /**
     * 删除指定数据     *      * @return
     */

    public int delete(BigInteger id) {
        return t_OrderMapper.delete(id);
    }

    /**
     * 根据条件统计数据量     *      * @return
     */

    public long count(T_OrderModel req) {
        return t_OrderMapper.count(req);
    }

    /**
     * 提交订单查询bonus
     * param {seller_user_id:卖家ID,price:购买金额}
     */
    @Transactional(rollbackFor = {
            Exception.class}, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public T_User_seller_bonusModel checkBonus(BigDecimal buy_count, String seller_user_id) {
        T_User_seller_bonusModel t_user_seller_bonusModel
                = new T_User_seller_bonusModel();
        t_user_seller_bonusModel.setUser_id(seller_user_id);
        DBContextHolder.setDbType(DBContextDbType.Master.name());
        List<T_User_seller_bonusModel> list =
                t_User_seller_bonusMapper.findByNamedParamList(t_user_seller_bonusModel);
        if (list == null || list.size() <= 0) {
            return null;
        }
        Collections.reverse(list);
        for (T_User_seller_bonusModel item : list) {
            if (buy_count.compareTo(new BigDecimal(item.getStart_count())) >= 0) {
                return item;
            }
        }
        return null;
    }

    /**
     * 组装log表
     */
    public T_Account_logModel init_account_log(String user_id, BigDecimal amount,
                                               String token_name, String type) {
        T_Account_logModel t_account_logModel = new T_Account_logModel();
        String tran_id = t_sequenceService.genSequence(SeqNameEnum.TRAN_ID);
        t_account_logModel.setTrans_id(tran_id);
        t_account_logModel.setAccount_no(user_id);
        t_account_logModel.setAmount(amount);
        t_account_logModel.setAmount_type(token_name);
        t_account_logModel.setType(type);
        t_account_logModel.setTrans_memo("");
        t_account_logModel.setOut_order_no("");
        t_account_logModel.setCreate_time(DateUtil.getToday());
        t_account_logModel.setModify_time(DateUtil.getToday());
        t_account_logModel.setUser_id(user_id);
        t_account_logModel.setWallet_address("");
        t_account_logModel.setStatus("1");
        return t_account_logModel;
    }

    /*
        预提交订单
     */
    public JsonResult drysubmit(DryOrderSubmitReq req) {
        //查询项目
        OrderSubmitInfoReq orderSubmitInfoReq = new OrderSubmitInfoReq();
        orderSubmitInfoReq.setPid(req.getPid());
        DBContextHolder.setDbType(DBContextDbType.Master.name());
        OrderProjectInfoResp orderProjectInfoResp = t_projectMapper.getProjectOrderInfo(orderSubmitInfoReq);
        if (orderProjectInfoResp == null) {
            //项目不存在
            return new JsonResult(HttpReturnRnums.ParaError);
        }

        T_Erc_contractModel ethModel = t_erc_contractMapper.selectETH();
        BigDecimal eth_count = req.getEth_price();
        int decimal = 0;
        int indexof = eth_count.toString().indexOf(".");
        if (indexof > 0) {
            decimal = eth_count.toString().length() - 1 - indexof;
        }
        if (decimal > 8) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }

        BigDecimal coin_count = t_usdt_exchange_priceService.exchageTokens(eth_count, orderProjectInfoResp.getContract_id(), req.getPid());

        String token_name = orderProjectInfoResp.getToken_name();
        String seller_user_id = orderProjectInfoResp.getSeller_user_id();

        //查询bonus
        BigDecimal bonus_value = new BigDecimal(100);
        int bonus_count = 0;
//        if (orderProjectInfoResp.getIssetbonus() != null && orderProjectInfoResp.getIssetbonus() == 1) {
        T_User_seller_bonusModel t_user_seller_bonusModel =
                ((T_OrderService) AopContext.currentProxy()).
                        checkBonus(coin_count, seller_user_id);
        bonus_value = t_user_seller_bonusModel.getBonus_value();
        bonus_count = t_user_seller_bonusModel.getStart_count();
//        }
        coin_count = coin_count.add(bonus_value);

        BigDecimal platform_commission = t_sysconfService.getPlatformCommission();
        BigDecimal buy_commission_rate = platform_commission.multiply(new BigDecimal(0.01));
        BigDecimal seller_commission_rate = platform_commission.multiply(new BigDecimal(0.01));

        HashMap<String, Object> ret = orderDecompostion(ethModel, orderProjectInfoResp, eth_count, coin_count, buy_commission_rate, seller_commission_rate);

        return new JsonResult(ret);
    }

    private HashMap<String, Object> orderDecompostion(
            T_Erc_contractModel ethModel,
            OrderProjectInfoResp orderProjectInfoResp,
            BigDecimal eth_count,
            BigDecimal coin_count,
            BigDecimal buyer_commission_rate,
            BigDecimal seller_commission_rate) {

        HashMap<String, Object> rst = new HashMap<>();
        int coin_digit = orderProjectInfoResp.getDigit();
        int cdigit = coin_digit < 8 ? coin_digit : 8;
        coin_count = coin_count.setScale(cdigit, BigDecimal.ROUND_UP);

        rst.put("seller_paid_coin_count", coin_count);
        rst.put("seller_paid_coin_name", orderProjectInfoResp.getToken_symbol());

        BigDecimal buyer_commission = coin_count.multiply(buyer_commission_rate).setScale(cdigit, BigDecimal.ROUND_UP);
        rst.put("buyer_commission", buyer_commission);

        BigDecimal seller_commission = eth_count.multiply(seller_commission_rate).setScale(8, BigDecimal.ROUND_UP);
        rst.put("seller_commission", seller_commission);
        rst.put("buyer_earned", coin_count.subtract(buyer_commission));
        rst.put("seller_earned", eth_count.subtract(seller_commission));

        return rst;
    }

    /**
     * 提交订单 TODO 提交订单，代码需要review
     */
    @Transactional(rollbackFor = {
            Exception.class}, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public JsonResult submit(OrderSubmitReq req) throws Exception {
        JsonResult js = new JsonResult();
        /**
         * 验证交易密码
         * */
        T_User_buyer_infoModel t_user_buyer_infoModel = new T_User_buyer_infoModel();
        t_user_buyer_infoModel.setUser_id(req.getBuyer_user_id());
        t_user_buyer_infoModel.setPassword(Digest.signMD5(req.getPay_pwd(), Digest.ENCODE));
        T_User_buyer_infoModel queryBuyerModel = t_user_buyer_infoMapper.findByNamedParam(t_user_buyer_infoModel);
        if (queryBuyerModel == null) {
            return new JsonResult(HttpReturnRnums.USER_ACCOUNT_PWD_ERROR);
        }
        if (!queryBuyerModel.getAuth_status().equals("1")) {
            return new JsonResult(HttpReturnRnums.USER_BUYER_KYC_NOT_AUTH_STATUS);
        }

        //查询项目
        OrderSubmitInfoReq orderSubmitInfoReq = new OrderSubmitInfoReq();
        orderSubmitInfoReq.setPid(req.getPid());
        DBContextHolder.setDbType(DBContextDbType.Master.name());
        OrderProjectInfoResp orderProjectInfoResp =
                t_projectMapper.getProjectOrderInfo(orderSubmitInfoReq);
        if (orderProjectInfoResp == null) {
            //项目不存在
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        /**
         * 判断买家不可购买的国家
         * */
        String buyerCountry = queryBuyerModel.getCountry();
        String notallow_country = orderProjectInfoResp.getNotallow_country();
        String[] arrNotCountry = notallow_country.split("\\|");
        for (String item :
                arrNotCountry) {
            if (item.equals(buyerCountry)) {
                return new JsonResult(HttpReturnRnums.PROJECT_COUNTRY_NOT_BUY);
            }
        }
        //换算代币
        BigDecimal eth_count = req.getEth_price();
        BigDecimal coin_count = t_usdt_exchange_priceService.exchageTokens(eth_count, orderProjectInfoResp.getContract_id(), req.getPid());
        //eth-USDT-token
        //写一个服务，eth->usdt的汇率（币安）
        String token_name = orderProjectInfoResp.getToken_name();
//        int buy_count = 100;
        //代币金额
//         new BigDecimal(50);
//        int coin_count=500;
        String seller_user_id = orderProjectInfoResp.getSeller_user_id();
        String buyer_user_id = req.getBuyer_user_id();
        //查询bonus
        BigDecimal bonus_value = new BigDecimal(100);
        String contractId = orderProjectInfoResp.getContract_id();
        int bonus_count = 0;
        if (orderProjectInfoResp.getIssetbonus() != null && orderProjectInfoResp.getIssetbonus() == 1) {
            //卖家开启了bonus
//            T_User_seller_bonusModel t_user_seller_bonusModel = checkBonus(coin_count, seller_user_id);
            T_User_seller_bonusModel t_user_seller_bonusModel =
                    ((T_OrderService) AopContext.currentProxy()).
                            checkBonus(coin_count, seller_user_id);
            bonus_value = t_user_seller_bonusModel.getBonus_value();
            bonus_count = t_user_seller_bonusModel.getStart_count();
        }
        //TODO ??这里应该是加吧？
        coin_count = coin_count.add(bonus_value);//卖家需要支付的代币总数
        //减买家ETH
        //BigDecimal eth_count, String buyer_user_id
        HashMap<String, Object> hash_deduction_buyer = new HashMap<String, Object>();
        hash_deduction_buyer.put("eth_count", eth_count);
        hash_deduction_buyer.put("contract_id", orderProjectInfoResp.getContract_id());
        hash_deduction_buyer.put("buyer_user_id", buyer_user_id);
        int deduction_buyer = t_OrderMapper.deduction_buyer_eth(hash_deduction_buyer);
        if (deduction_buyer <= 0) {
            throw new Exception("买家余额不足");
        }
        //减卖家代币
        HashMap<String, Object> hash_buy_count = new HashMap<String, Object>();
        hash_buy_count.put("buy_count", coin_count);
        hash_buy_count.put("seller_user_id", seller_user_id);
        hash_buy_count.put("pid", req.getPid());
        int deduction_seller = t_OrderMapper.deduction_seller_coin(hash_buy_count);
        if (deduction_seller <= 0) {
            throw new Exception("卖家代币不足");
        }

        //查询手续费,平台佣金
        BigDecimal platform_commission = t_sysconfService.getPlatformCommission();
        //增加卖家eth手续费记录 account_log
        /*平台手续费百分比*/
        BigDecimal p_commission = platform_commission.multiply(new BigDecimal(0.01));
        //卖家支付eth平台佣金
        BigDecimal platform_eth_price = eth_count.multiply(p_commission).setScale(18, BigDecimal.ROUND_UP);
        //卖家eth收到金额
        BigDecimal pay_eth_price = eth_count.subtract(platform_eth_price);
        //买家支付coin平台佣金
        BigDecimal platform_coin_price = coin_count.multiply(p_commission).
                setScale(orderProjectInfoResp.getDigit(), BigDecimal.ROUND_UP);
        //买家coin收到的金额
        BigDecimal pay_coin_price = coin_count.subtract(platform_coin_price);
        String order_id = t_sequenceService.genSequence(SeqNameEnum.ORDER_ID);
        /**
         * 创建订单开始
         * */
        T_OrderModel t_orderModel = new T_OrderModel();
        t_orderModel.setPid(req.getPid());
        t_orderModel.setBuy_count(coin_count);
        t_orderModel.setBonus(bonus_value);
        t_orderModel.setBonus_count(new BigDecimal(bonus_count));
        t_orderModel.setFinal_buy_count(pay_coin_price);
        t_orderModel.setFinal_sell_count(pay_eth_price);
        t_orderModel.setToken_price(coin_count);
        /*买家支付token数*/
        t_orderModel.setBuyer_paid(coin_count);
        /*卖家收到token数（buyer_paid - seller_platform_commission）*/
        t_orderModel.setSeller_earned(pay_coin_price);
        t_orderModel.setBuyer_platform_commission(platform_coin_price);
        t_orderModel.setToken_name(token_name);
        t_orderModel.setToken_site("");
        t_orderModel.setPay_status(1);
        t_orderModel.setOid(order_id);
        t_orderModel.setSeller_user_id(seller_user_id);
        t_orderModel.setBuyer_user_id(buyer_user_id);
        int order_result = t_OrderMapper.insert(t_orderModel);
        if (order_result <= 0) {
            throw new Exception("参数错误");
        }
        /**
         * 创建 order_kyc
         * */
        int order_kyc_result = t_order_kycMapper.insertOrderKyc(t_orderModel);
        if (order_kyc_result <= 0) {
            throw new Exception("参数错误");
        }
        /**
         * 创建订单结束
         * */
        List<T_Account_logModel> listLog = new ArrayList<T_Account_logModel>();

        //支出买家eth
        T_Account_logModel model_jian_buyer_eth = init_account_log(buyer_user_id, eth_count, Util.getETHID(), "支出");
        //支出买家代币手续费记录 account_log
        T_Account_logModel model_buyer_coin_comssion = init_account_log(buyer_user_id, platform_coin_price, token_name, "支出");
        //增加收入买家代币金额
        T_Account_logModel model_buyer_coin = init_account_log(buyer_user_id, pay_coin_price, token_name, "收入");

        //支出卖家coin
        T_Account_logModel model_jian_seller_coin = init_account_log(seller_user_id, coin_count, token_name, "支出");
        //支出卖家eth手续费记录
        T_Account_logModel model_seller_eth_comssion = init_account_log(seller_user_id, platform_eth_price, Util.getETHID(), "支出");
        //卖家收入eth
        T_Account_logModel model_seller_eth = init_account_log(seller_user_id, pay_eth_price, Util.getETHID(), "收入");

        listLog.add(model_jian_buyer_eth);
        listLog.add(model_buyer_coin_comssion);
        listLog.add(model_buyer_coin);
        listLog.add(model_jian_seller_coin);
        listLog.add(model_seller_eth_comssion);
        listLog.add(model_seller_eth);
        int result = t_account_logMapper.insertBatch(listLog);
        if (result <= 0) {
            throw new Exception("记录日志错误");
        }
        /**
         * 查询买家代币钱包里是否有该代币
         * */
        DBContextHolder.setDbType(DBContextDbType.Master.name());
        T_Wallet_infoModel t_wallet_infoModel = new T_Wallet_infoModel();
        t_wallet_infoModel.setUser_id(buyer_user_id);
        t_wallet_infoModel.setContract_id(orderProjectInfoResp.getContract_id());
        int walletCount = t_wallet_infoMapper.count(t_wallet_infoModel);
        //为买家代币账户里增加余额  买家钱包增加余额
        if (walletCount <= 0) {
            //不存在 ，创建钱包
            T_Wallet_infoModel t_wallet_infoModel1 = new T_Wallet_infoModel();
            t_wallet_infoModel1.setContract_id(orderProjectInfoResp.getContract_id());
            t_wallet_infoModel1.setUser_id(buyer_user_id);
            t_wallet_infoModel1.setAmount(pay_coin_price);
            t_wallet_infoModel1.setFreeze_amount(new BigDecimal(0));
            t_wallet_infoModel1.setWithdraw_amount(new BigDecimal(0));
            t_wallet_infoModel1.setStatus("1");
            t_wallet_infoMapper.insert(t_wallet_infoModel1);
        } else {
            //存在则修改钱包金额
            HashMap<String, Object> hashBuyerPrice = new HashMap<String, Object>();
            hashBuyerPrice.put("user_id", buyer_user_id);
            hashBuyerPrice.put("contract_id", contractId);
            hashBuyerPrice.put("amount", pay_coin_price);
            t_wallet_infoMapper.buyerAmountAdd(hashBuyerPrice);
        }

        //为卖家ETH账户里增加余额   卖家钱包增加余额
        HashMap<String, Object> hashSellerPrice = new HashMap<String, Object>();
        hashSellerPrice.put("user_id", seller_user_id);
        hashSellerPrice.put("contract_id", Util.getETHID());
        hashSellerPrice.put("amount", pay_eth_price);
        t_wallet_infoMapper.buyerAmountAdd(hashSellerPrice);

        //tbalance添加卖家佣金记录  管理后台收入
        T_BalanceModel t_balanceModelSeller = new T_BalanceModel();
        t_balanceModelSeller.setToken_type(Util.getETHID());
        t_balanceModelSeller.setTrans_type("手续费收入");
        t_balanceModelSeller.setTrans_id(model_seller_eth_comssion.getTrans_id());
        t_balanceModelSeller.setValue(model_seller_eth_comssion.getAmount());
        //tbalance添加买家佣金记录  管理后台收入
        T_BalanceModel t_balanceModelBuyer = new T_BalanceModel();
        t_balanceModelBuyer.setToken_type(contractId);
        t_balanceModelBuyer.setTrans_type("手续费收入");
        t_balanceModelBuyer.setTrans_id(model_buyer_coin_comssion.getTrans_id());
        t_balanceModelBuyer.setValue(model_buyer_coin_comssion.getAmount());

        List<T_BalanceModel> t_balanceModelList = new ArrayList<T_BalanceModel>();
        t_balanceModelList.add(t_balanceModelBuyer);
        t_balanceModelList.add(t_balanceModelSeller);
        t_balanceMapper.insertBatch(t_balanceModelList);
        //购买加积分
        t_integral_recordService.threadInsertIntegralRecord(
                IntegralRecordEnum.GMICO, order_id, req.getBuyer_user_id());
        return js;
    }

    /**
     * 获取提交订单信息
     */
    public JsonResult getSubmitInfo(OrderSubmitInfoReq req) {
        JsonResult js = new JsonResult();
        OrderProjectInfoResp resp =
                t_projectMapper.getProjectOrderInfo(req);
        if (resp == null) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
//        if (resp.getIssetbonus() != null && resp.getIssetbonus() == 1) {
        //开启了bonus
//            String seller_user_id = resp.getUser_id();
        T_User_seller_bonusModel t_user_seller_bonusModel
                = new T_User_seller_bonusModel();
        t_user_seller_bonusModel.setUser_id(resp.getSeller_user_id());
        List<T_User_seller_bonusModel> t_user_seller_bonusModelList =
                t_User_seller_bonusMapper.findByNamedParamList(t_user_seller_bonusModel);
        if (t_user_seller_bonusModelList != null &&
                t_user_seller_bonusModelList.size() > 0) {
            resp.setT_user_seller_bonusModelList(t_user_seller_bonusModelList);
        }
//        }
        OrderProjectInfoResp respUserInfo =
                t_user_walletMapper.getOrderInfo(req);
        if (respUserInfo == null || respUserInfo.getStatus() != 1) {
            //账户异常
            return new JsonResult(HttpReturnRnums.USER_ACCOUNT_ERROR);
        }
        resp.setAmount(respUserInfo.getAmount());
        resp.setStatus(respUserInfo.getStatus());
        resp.setEmail(respUserInfo.getEmail());
        BigDecimal platform_commission = t_sysconfService.getPlatformCommission();
        //平台佣金
        resp.setPlatform_commission(platform_commission);
        js.setData(resp);
        return js;
    }

    /**
     * 获取B端的订单里列表
     */
    public JsonResult getOrderList(OrderExportReq req) {
        JsonResult js = new JsonResult();
        String ticker_name = t_projectMapper.getTickerByUserId(req.getSeller_user_id());
        OrderExportResp resp = new OrderExportResp();
        /**
         * 组装总金额开始
         * */
        OrderCounterResp orderCounterResp = t_OrderMapper.getOrderListCounter(req);
        orderCounterResp = orderCounterResp == null ? new OrderCounterResp() : orderCounterResp;
        BigDecimal all_corn = orderCounterResp.getAll_corn() == null ? BigDecimal.ZERO : orderCounterResp.getAll_corn().setScale(8, BigDecimal.ROUND_UP);
        ;
        resp.setAll_corn(all_corn + " " + ticker_name);
        BigDecimal all_eth = orderCounterResp.getAll_eth() == null ? BigDecimal.ZERO : orderCounterResp.getAll_eth().setScale(8, BigDecimal.ROUND_UP);
        ;
        resp.setAll_eth(all_eth + " ETH");
        BigDecimal platform_commission = orderCounterResp.getPlatform_commission() == null ? BigDecimal.ZERO : orderCounterResp.getPlatform_commission().setScale(8, BigDecimal.ROUND_UP);
        resp.setPlatform_commission(platform_commission + " ETH");
        /**
         * 组装总金额结束
         * */
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        Page<OrderExportBigDecimalBaseResp> orderExportBaseRespList = t_OrderMapper.getOrderList(req);
        List<OrderExportBaseResp> list = convertExportBaseRespList(orderExportBaseRespList, ticker_name);
        PageInfoExt<OrderExportBaseResp> pageExt = new PageInfoExt<OrderExportBaseResp>(list,
                orderExportBaseRespList.getTotal(), req.getPage_index(),
                req.getPage_size());
        resp.setList(pageExt);
        js.setData(resp);
        return js;
    }

    private List<OrderExportBaseResp> convertExportBaseRespList(List<OrderExportBigDecimalBaseResp> list,
                                                                String coin_name) {
        /**
         * 组装订单列表开始
         * */
        List<OrderExportBaseResp> listResult = new ArrayList<OrderExportBaseResp>();
        for (OrderExportBigDecimalBaseResp item : list) {
            OrderExportBaseResp model = new OrderExportBaseResp();
            model.setCreate_time(item.getCreate_time());
            model.setEmail(item.getEmail());
            model.setOid(item.getOid());
            model.setUser_id(item.getUser_id());
            if (item.getSelle_token().compareTo(BigDecimal.ZERO) >= 0) {
                model.setSelle_token(item.getSelle_token().setScale(8, BigDecimal.ROUND_UP) + " " + coin_name);
            }
            if (item.getObtain_token().compareTo(BigDecimal.ZERO) >= 0) {
                model.setObtain_token(item.getObtain_token().setScale(8, BigDecimal.ROUND_UP) + " ETH");
            }
            if (item.getSeller_platform_commission().compareTo(BigDecimal.ZERO) >= 0) {
                model.setSeller_platform_commission(item.getSeller_platform_commission().setScale(8, BigDecimal.ROUND_UP) + " ETH");
            }
            listResult.add(model);
        }

        return listResult;
        /**
         * 组装订单列表结束
         * */
    }

    public void getExportOrderList(OrderExportReq req,
                                   HttpServletRequest request, HttpServletResponse response) {

        /**
         * 根据卖家用户ID，获取token_name
         * */
        JsonResult js = new JsonResult();
        String ticker_name = t_projectMapper.getTickerByUserId(req.getSeller_user_id());
        List<OrderExportBigDecimalBaseResp> orderExportBaseRespList = t_OrderMapper.getOrderList(req);
        List<OrderExportBaseResp> list = convertExportBaseRespList(orderExportBaseRespList, ticker_name);
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("购买用户账号", "email");
        map.put("售出token", "selle_token");
        map.put("获取token", "obtain_token");
        map.put("平台抽佣token", "seller_platform_commission");
        map.put("购买时间", "create_time");
        try {
            ExcelUtils.export2Excel("order-list",
                    "order-list", map, list, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //public

}